package com.example.wan1.view.wechat;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.wan1.R;
import com.example.wan1.adapter.ArticleListAdapter;
import com.example.wan1.base.fragment.SimpleFragment;
import com.example.wan1.bus.RxBus;
import com.example.wan1.event.CollectEvent;
import com.example.wan1.model.ArticleBean;
import com.example.wan1.model.KnowledgeBean;
import com.example.wan1.model.common.CommonResList;
import com.example.wan1.utils.ToastUtils;
import com.example.wan1.view.collect.HandleCollectTool;
import com.example.wan1.view.login.UserManager;
import com.example.wan1.view.web.JumpTool;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/***
 * 创建时间：2020/7/11 9:51
 * 创建人：10850
 * 功能描述：为什么做成fragment，就是想之后，把公众号这个界面放到下面的tab中去
 * 1.使用基础的类，实现tab+vp
 * 2.弄一个
 *
 * 3.可以尝试使用两个rv来实现公众号功能，一个横向的，一个纵向的
 */
public class WeChatFragment extends SimpleFragment implements WeChatContract.View, OnRefreshListener,
        OnLoadMoreListener {

    @BindView(R.id.srlheader)
    MaterialHeader mSrlheader;
    @BindView(R.id.srl)
    SmartRefreshLayout mSrl;
    @BindView(R.id.wechat_rv)
    RecyclerView mWechatRv;
    @Inject
    ArticleListAdapter mAdapter;
    @Inject
    List<ArticleBean> mList;
    @Inject
    WechatPresenter mPresenter;

    private int curPage = 1;
    private int id;

    @Override
    protected int initLayoutRes() {
        return R.layout.fragment_wechat;
    }

    @Override
    protected void initData() {
        mPresenter.getWechatDataList(id, curPage);
    }

    @Override
    protected void initView() {
        showLoading();

        mWechatRv.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter.bindToRecyclerView(mWechatRv);

        mSrl.setOnLoadMoreListener(this);
        mSrl.setOnRefreshListener(this);

        mSrl.setEnableRefresh(false);
        mSrl.setEnableLoadMore(false);

        mAdapter.setOnItemClickListener((baseQuickAdapter, view, i) -> {
            JumpTool.goWeb(mContext, mList.get(i).getTitle(), mList.get(i).getLink());
            HandleCollectTool.getInstance().setInfo(mList.get(i), i, "文章");
        });

        mAdapter.setOnItemChildClickListener((baseQuickAdapter, view12, i) -> {
            switch (view12.getId()) {
                case R.id.article_iv_collect: {
                    if (!UserManager.getInstance().isLogin()) {
                        JumpTool.goLogin(getActivity());
                        return;
                    }
                    ArticleBean articleBean = mList.get(i);
                    HandleCollectTool.getInstance().setInfo(articleBean, i, "文章");
                    ImageView iv = view12.findViewById(R.id.article_iv_collect);
                    if (articleBean.isCollect()) {
                        HandleCollectTool.getInstance().cancelList();
                        iv.setImageResource(R.mipmap.heart_gray);
                    } else {
                        HandleCollectTool.getInstance().collectIn();
                        iv.setImageResource(R.mipmap.heart_red);
                    }
                }
                break;
            }
        });

        mWechatRv.addOnScrollListener(mOnScrollListener);
    }

    @Override
    public void onSuccess(CommonResList<ArticleBean> data) {
        hideLoading();
        if (data.getDatas().size() != 0) {
            mSrl.setEnableRefresh(true);
            mSrl.setEnableLoadMore(true);
            mAdapter.addData(data.getDatas());
            mAdapter.notifyDataSetChanged();
            curPage = data.getCurPage() + 1;
        }
        if (data.isOver()) {
            mAdapter.loadMoreEnd();
            if (mAdapter.getFooterLayoutCount() == 0) {
                View footer = LayoutInflater.from(mContext).inflate(R.layout.loadmore_view, null);
                mAdapter.addFooterView(footer);
            }
            mSrl.setEnableLoadMore(false);
        }
    }

    @Override
    public void onFailure(String msg) {
        showError();
        mSrl.setEnableLoadMore(false);
        mSrl.setEnableRefresh(false);
        ToastUtils.showToast(msg);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mWechatRv.postDelayed(() -> {
            mPresenter.getWechatDataList(id, curPage);
            mSrl.finishLoadMore(true);
        }, 200);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mWechatRv.postDelayed(() -> {
            mList.clear();
            mPresenter.getWechatDataList(id, 1);
            mSrl.finishRefresh(true);
        }, 200);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        id = getArguments().getInt(PARAM, 0);
    }

    private static String PARAM = "ID";

    public WeChatFragment newInstance(int id) {
        WeChatFragment baseFragment = new WeChatFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(PARAM, id);
        baseFragment.setArguments(bundle);
        return baseFragment;
    }

    @Override
    public void onGetTitle(List<KnowledgeBean> titles) {

    }

    public void notifyItemCollect() {
        if (mWechatRv.getAdapter() == null)
            mAdapter.bindToRecyclerView(mWechatRv);
        int pos = HandleCollectTool.getInstance().getPosition();
        mAdapter.notifyItemChanged(pos);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        RxBus.getDefault().subscribeSticky(mContext, new RxBus.Callback<CollectEvent>() {
            @Override
            public void onEvent(CollectEvent collectEvent) {
                if ("文章".equals(collectEvent.getType()))
                    notifyItemCollect();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(mContext);
    }
}
